package com.csz.servlet;

import com.csz.bean.Student;
import com.csz.service.StudentService;
import com.csz.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/Educational/student/getStudentList")
public class getStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取数据
            //1.1模糊查询的数据
        String stuname = req.getParameter("stuname");
        String stuno = req.getParameter("stuno");
        String sex = req.getParameter("sex");
        int usex=(sex==null||sex.length()==0?-1:Integer.parseInt(sex));
        /*
         System.out.println(sex);
        System.out.println(stuname);
        System.out.println(stuno);
         */
            //1.2 分页查询的数据  数据库语句 limit(开始位置，显示多少条数据)
        String pageIndex = req.getParameter("pageIndex"); // 当前页码值
        //如果页面没有传入pageindex则默认查询第一页
        int index = pageIndex==null?1:Integer.parseInt(pageIndex);
        // 获取总页数  =总条数%pageSize>0?总条数/pageSize +1 : 总条数/pageSize


        //2. 调取service方法
         //2.1 创建service对象
        StudentService service = new StudentServiceImpl();
        List<Student> students = service.getStudents(stuname,stuno,usex,index,5);
        // 获取总条数
        int total = service.total(stuname,stuno,usex); // 总条数
        int totalPage = total%5>0?(total/5)+1:total/5;   // 总页数

        //2.2后台的内容，输出到前台，需要存值
        req.setAttribute("slist",students);
         //2.3  存储模糊查询中的值
        req.setAttribute("stuname",stuname);
        req.setAttribute("stuno",stuno);
        req.setAttribute("sex",sex);

            // 存贮分页数据
        req.setAttribute("index",index);
        req.setAttribute("size",5);
        req.setAttribute("total",total);
        req.setAttribute("totalPage",totalPage);
        //3. 跳转页面
         //如果使用resp重定向，会丢失req中的数据
            // 因为需要在页面展示数据，所以使用转发的方式.

        req.getRequestDispatcher("list.jsp").forward(req,resp);
        /*
        在list.jsp页面中，使用el和jsp语句，遍历输出
         */
    }
}
